#*--------------------------------------------------------------------------------
# DESCRIPTION: Creating Appendix Figure G1-G2
#
#--------------------------------------------------------------------------------#

install.packages(c("fect","haven", "fixest", "ggplot2", "extrafont", "dplyr", "stringr", "flextable", "officer"))

library(dplyr)
library(extrafont)
library(fect)
library(fixest)
library(ggplot2)
library(haven)
library(stringr)
library(flextable)
library(officer)

font_import()
loadfonts(device = "win")

##############################################################################################################
##SET RELEVANT WORKING DIRECTORY
setwd("...") 

##############################################################################################################
##PREPARE DATA
data <- read_dta("data/clean/country_year_panel.dta")
df.use <- data[!is.na(data$growth_shock_mpd),]
df.use <- data.frame(df.use)
df.use <- get.cohort(data = df.use, D = "growth_shock_mpd",index = c("panelid","year"))

#############################################################################################################################

######################
##Create Figure G1##
######################

# Filter to just Control and Cohort:2009
data_cohort <- subset(df.use, Cohort %in% c("Control", "Cohort:2009"))

data_cohort$treat <- 0
data_cohort[data_cohort$Cohort == "Cohort:2009", "treat"] <- 1
data_cohort[is.na(data_cohort$Time_to_Treatment), "treat"] <- 0

remove <- intersect(which(is.na(data_cohort$Time_to_Treatment)), which(data_cohort$growth_shock_mpd == 1))
if(length(remove) > 0) {
  data_cohort <- data_cohort[-remove, ]
}

data_cohort[is.na(data_cohort$Time_to_Treatment), "Time_to_Treatment"] <- 999

twfe.est <- feols(trust_govt_wo ~ i(Time_to_Treatment, treat, ref = -1) | ccode + year,  
                  data = data_cohort, cluster = "ccode")

twfe.output <- as.data.frame(twfe.est$coeftable)
twfe.output$Time <- as.numeric(gsub("Time_to_Treatment::(-?\\d+):treat", "\\1", rownames(twfe.output)))
twfe.output <- twfe.output[order(twfe.output$Time), ]
twfe.output$CI.lower <- twfe.output$Estimate - 1.96 * twfe.output$`Std. Error`
twfe.output$CI.upper <- twfe.output$Estimate + 1.96 * twfe.output$`Std. Error`
colnames(twfe.output)[1] <- "ATT"
colnames(twfe.output)[2] <- "S.E."
colnames(twfe.output)[4] <- "p.value"
twfe.output <- twfe.output[, c("Time", "ATT", "S.E.", "CI.lower", "CI.upper", "p.value")]
twfe.output$Model <- "TWFE"

baseline_row <- data.frame(
  Time = -1,
  ATT = 0,
  `S.E.` = NA,
  CI.lower = NA,
  CI.upper = NA,
  p.value = NA,
  Model = "TWFE"
)

twfe.output <- rbind(twfe.output, baseline_row)
twfe.output <- twfe.output[order(twfe.output$Time), ]

dpi=600    #pixels per square inch
png("output/figures/appendix_g/figure_g1.png", width=6*dpi, height=5*dpi, res=dpi)
figure_g1 <- ggplot(twfe.output, aes(x = Time, y = ATT)) +
  geom_hline(yintercept = 0, colour = "firebrick4") +
  geom_vline(xintercept = -1, colour = "firebrick4", linetype = 'dashed') +
  geom_errorbar(aes(ymin = CI.lower, ymax = CI.upper), width = 0.2, color = "black") +
  geom_point(color = "black", size = 1.85, shape = 21, fill = "steelblue4") + 
  theme(text = element_text(family = "Palatino"),
        panel.background = element_rect(fill = 'white', color = 'black'),
        panel.grid.major = element_line(color = gray(1/4), size = 0.2, linetype = 'dotted'),
        panel.grid.minor = element_line(color = gray(1/4), size = 0.2, linetype = 'dotted'),
        axis.text = element_text(size = 12, colour = "black"),
        axis.title = element_text(size = 12),
        title = element_text(size = 13)) +
  coord_cartesian(xlim = c(-4, 3)) + ylim(-0.25, 0.2) +
  scale_x_continuous(breaks = seq(-4, 3, 1)) +
  ylab("Effect on Trust in Government") +
  xlab("Time to 2008 Financial Crisis")
figure_g1
dev.off()


#############################################################################################################################

######################
##Create Figure G2##
######################

model.cfe <- fect(trust_govt_wo ~ growth_shock_mpd, data = df.use, 
                  index = c("panelid","year"), cfe = list(c("panelid", "year")), 
                  force = "two-way", method = "cfe", CV = TRUE, alpha = 0.05, seed = 1234,
                  se = TRUE, nboots = 200, parallel = TRUE, group = "Cohort")

##ENTERING TREATMENT
ci_bounds <- model.cfe[["est.group.output"]][["Cohort:2009"]][["att.on.bound"]]
att <- model.cfe[["group.output"]][["Cohort:2009"]][["att.on"]]
time <- model.cfe[["group.output"]][["Cohort:2009"]][["time.on"]]
cfe.output <- data.frame(
  Time = time,
  ATT = att,
  CI.lower = ci_bounds[, 1],
  CI.upper = ci_bounds[, 2]
)

dpi=600    #pixels per square inch
png("output/figures/appendix_g/figure_g2_a.png", width=6*dpi, height=5*dpi, res=dpi)
figure_g2_a <- ggplot(cfe.output, aes(x = Time, y = ATT)) +
  geom_hline(yintercept = 0, colour = "firebrick4") +
  geom_vline(xintercept = 0, colour = "firebrick4", linetype = 'dashed') +
  geom_errorbar(aes(x = Time, 
                    ymin = CI.lower,
                    ymax = CI.upper), width=.2, color = "black") + 
  geom_point(aes(x = Time, y = ATT), color = "black", size=1.85, shape=21, fill = "darkgreen") + 
  theme(text = element_text(family = "Palatino"),
        panel.background = element_rect(fill = 'white', color = 'black'),
        panel.grid.major = element_line(color = gray(1/4), size = 0.2, linetype = 'dotted'),
        panel.grid.minor = element_line(color = gray(1/4), size = 0.2, linetype = 'dotted'),
        axis.text.x = element_text(colour = "black"),
        axis.text.y = element_text(colour = "black"),
        axis.text=element_text(size=12), 
        axis.title=element_text(size=12.5),
        title=element_text(size=13)) +
  coord_cartesian(xlim=c(-3.1,3.1)) + ylim(-0.25,0.2) + scale_x_continuous(breaks=seq(-3, 3, 1)) + 
  ylab("Effect on Trust in Government") + 
  xlab("Time to 2008 Financial Crisis")
figure_g2_a
dev.off()

##EXIT TREATMENT
ci_bounds <- model.cfe[["est.group.output"]][["Cohort:2009"]][["att.off.bound"]]
att <- model.cfe[["group.output"]][["Cohort:2009"]][["att.off"]]
time <- model.cfe[["group.output"]][["Cohort:2009"]][["time.off"]]
cfe.output.exit <- data.frame(
  Time = time,
  ATT.OFF = att,
  CI.lower = ci_bounds[, 1],
  CI.upper = ci_bounds[, 2]
)

dpi=600    #pixels per square inch
png("output/figures/appendix_g/figure_g2_b.png", width=6*dpi, height=5*dpi, res=dpi)
figure_g2_b <- ggplot(cfe.output.exit, aes(x = Time, y = ATT.OFF)) +
  geom_hline(yintercept = 0, colour = "firebrick4") +
  geom_vline(xintercept = 0, colour = "firebrick4", linetype = 'dashed') +
  geom_errorbar(aes(x = Time, 
                    ymin = CI.lower,
                    ymax = CI.upper), width=.2, color = "black") + 
  geom_point(aes(x = Time, y = ATT.OFF), color = "black", size=1.85, shape=21, fill = "darkgreen") + 
  theme(text = element_text(family = "Palatino"),
        panel.background = element_rect(fill = 'white', color = 'black'),
        panel.grid.major = element_line(color = gray(1/4), size = 0.2, linetype = 'dotted'),
        panel.grid.minor = element_line(color = gray(1/4), size = 0.2, linetype = 'dotted'),
        axis.text.x = element_text(colour = "black"),
        axis.text.y = element_text(colour = "black"),
        axis.text=element_text(size=12), 
        axis.title=element_text(size=12.5),
        title=element_text(size=13)) +
  coord_cartesian(xlim=c(-2.1,4.1)) + ylim(-0.25,0.2) + scale_x_continuous(breaks=seq(-2, 4, 1)) + 
  ylab("Effect on Trust in Government") + 
  xlab("Time to Exiting 2008 Financial Crisis")
figure_g2_b
dev.off()
